/**
 * 
 */
package info.niwota.frames;

import java.io.File;
import java.io.FileNotFoundException;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.util.Log;

/**
 * @author qiangli
 * 
 */
public class PeerUriImage extends UriImage {

	private static final String TAG = "PeerUriImage";
	private ImageFrame frame;
	private Context ctx;
	private int pos;

	/**
	 * @param cr
	 * @param uri
	 */
	public PeerUriImage(ImageFrame frame, Context ctx, Uri uri, int pos) {
		super(ctx.getContentResolver(), uri);
		this.ctx = ctx;
		this.frame = frame;
		this.pos = pos;
	}

	@Override
	public Bitmap fullSizeBitmap(int minSideLength, int maxNumberOfPixels,
			boolean x, boolean useNative) {

		File f = null;
		try {
			f = FrameHelper.getCachedPeerImage(ctx, mUri, frame.getLastModified());
			return bitmap(f, minSideLength, maxNumberOfPixels, useNative);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private Bitmap bitmap(File file, int minSideLength, int maxNumberOfPixels,
			boolean useNative) {
		try {
			if (Debug.DEBUG) {
				Log.d(TAG, "bitmap: file: " + file);
			}
			ParcelFileDescriptor fd = ParcelFileDescriptor.open(file,
					ParcelFileDescriptor.MODE_READ_ONLY);

			Bitmap b = Util.makeBitmap(minSideLength, maxNumberOfPixels, fd,
					useNative);

			return b;
		} catch (Error e) {
			// Log.e(TAG, "got exception decoding bitmap ", e);
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public Bitmap miniThumbBitmap() {
		return thumbBitmap(IImage.ROTATE_AS_NEEDED);
	}

	@Override
	public Bitmap thumbBitmap(boolean rotateAsNeeded) {
		String[] pa = frame.getPeerLabel();
		String peer = pa[0];
		String label = pa[1];

		File file;
		try {
			file = FrameHelper.getCachedPeerThumbnail(ctx, peer, label, pos);

			return bitmap(file, MINI_THUMB_TARGET_SIZE,
					MINI_THUMB_MAX_NUM_PIXELS, IImage.NO_NATIVE);
		} catch (Exception e) {
			if (Debug.DEBUG) {
				Log.d(TAG, "pos: " + pos);
			}
			e.printStackTrace();
		}
		return null;
	}

}
